﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Macds.Core
{
    /// <summary>
    /// Extend your custom class in order tu use the prototype pattern
    /// </summary>
    [Serializable]
    public abstract class ClonableBase : ICloneable
    {

        #region ICloneable Members

        public object Clone()
        {
            return this.MemberwiseClone();
        }

        #endregion

        #region ICloneable Members Extension

        public object Clone(bool shallow)
        {
            return shallow ? Clone() : DeepCopy();
        }

        public object DeepCopy()
        {
            var stream = new MemoryStream();
            var formatter = new BinaryFormatter();

            formatter.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);

            object copy = formatter.Deserialize(stream);
            stream.Close();

            return copy;
        }

        #endregion
    }
}
